from system.object import Object
from system.eventServer import eventServer
from system.vec2 import Vec2
from system.timer import Timer

import math

class Bullet(Object):
    def __init__(self, parent, type = None, name = None):
        Object.__init__(self, parent, type, name)
        
        self.defaultVar("gfx","bulletgfx")
        self.defaultVar("speed",200)
        self.defaultVar("damage",1)
        self.defaultVar("lifeTime",2.0)
        self.defaultVar("scale",(10,10))
        self.defaultVar("renderOp2d","sceneNode")
        
        eventServer.register("update",self.update)
        
    def init(self):
        self.target = self.getObject(self.getVar("target"))
        
        self.deathTimer = Timer(self.getVar("lifeTime"))

        self.gfx = self.addChild(self.getVar("gfx"),"gfx")
        self.gfx.setVar("static",True)
        self.gfx.setVar("rot",-math.pi/2)
        
        rot = self.getVar("rot")
        speed = self.getVar("speed")
        self.vel = Vec2(math.cos(rot)*speed,math.sin(rot)*speed)
        
        points = self.flattenVars("points")
        if points:
            sumx = sumy = count = 0
            for px, py in points:
                sumx += px
                sumy += py
                count += 1
                
            cx = sumx / float(count)
            cy = sumy / float(count)
            
        else:
            cx = cy = 0.5
            
        maxDist = None
        for px, py in points:
            dx = px - cx
            dy = py - cy
            dist = math.sqrt(dx * dx + dy * dy)
            if not maxDist or dist > maxDist:
                maxDist = dist
        if not maxDist:
            maxDist = 1
            
        self.setVar("center",(cx,cy))
        self.setVar("boundingRadius",maxDist)
        self.gfx.setVar("pos",(-cx,-cy))
        
    #HACK -dtime
    def update(self, cmd, args):
        dtime = -abs(args['dtime'])
        self.setVar("pos",(Vec2(self.getVar("pos")) + self.vel * dtime).toTuple())
        
        if self.target and not self.target.getVar("dead"):
            mySize = self.getVar("boundingRadius") * self.getVar("scale")[0]
            if self.target.hasVar('boundingRadius') and self.target.hasVar("scale"):
                targetSize = self.target.getVar("boundingRadius") * self.target.getVar("scale")[0]
            else:
                targetSize = 0
            dist = (Vec2(self.target.getVar("pos")) - Vec2(self.getVar("pos"))).length()
            if dist < mySize + targetSize:
                #netPull?
                eventServer.pull('unitDamage',{'path':self.target.getVar("path"),'damage':self.getVar("damage")})
                #self.target.receiveDamage(self.getVar("damage"))
                self.parent.removeChild(self.getVar("name"))
        
        if self.deathTimer.fire():
            self.parent.removeChild(self.getVar("name"))
